package com.bbzn.user.client.controller;

import com.bbzn.device.client.DeviceClient;
import com.bbzn.device.client.FenceClient;
import com.bbzn.user.client.aspect.OperationAnnotation;
import com.bbzn.user.client.constant.*;
import com.bbzn.user.client.dataobject.*;
import com.bbzn.user.client.dto.user.UserInfoDTO;
import com.bbzn.user.client.dto.user.UserProcessDTO;
import com.bbzn.user.client.exception.DefinitException;
import com.bbzn.user.client.service.*;
import com.bbzn.user.client.utils.*;
import com.bbzn.user.client.vo.req.ChangeVO;
import com.bbzn.user.client.vo.req.UserProcessVO;
import com.bbzn.user.client.vo.req.UserRoleVO;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Author wulongbo
 * @Date 2021/3/22 14:30
 * @Version 1.0
 */

@RestController
@RequestMapping("/user")
@Slf4j
@Api(value = "User", tags = "用户管理器")
public class UserController extends BaseApiService {

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private TenantService tenantService;

    @Autowired
    private UserProcessService userProcessService;

    @Autowired
    private CommonService commonService;

    @Autowired
    private SystemParamByCacheService systemParamByCacheService;

    @Autowired
    private DeviceClient deviceClient;

    @Autowired
    private FenceClient fenceClient;

    @Autowired
    private RedisUtils redisUtil;

    @PostMapping("/selectSelective")
    @OperationAnnotation(content = "Feign暴露接口：用户信息根据条件查询")
    public List<com.bbzn.user.comment.User> selectSelective(@RequestBody User record) throws Exception {
        List<User> users  = userService.findByAll(record);
        List<com.bbzn.user.comment.User> userResList = users.stream().parallel().map(user -> {
            com.bbzn.user.comment.User userRes = new com.bbzn.user.comment.User();
            try {
                BeanUtils.copyProperties(userRes,user);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
            return userRes;
        }).filter(Objects::nonNull).collect(Collectors.toList());
        return userResList;
    }

    @PostMapping("/selectBatchIds")
    @OperationAnnotation(content = "Feign暴露接口：根据userID批量查询")
    public List<com.bbzn.user.comment.User> selectBatchIds(@RequestBody List<Long> ids) throws Exception {
        List<User> users = userService.selectBatchIds(ids);
        List<com.bbzn.user.comment.User> userResList = users.stream().parallel().map(user -> {
            com.bbzn.user.comment.User userRes = new com.bbzn.user.comment.User();
            try {
                BeanUtils.copyProperties(userRes,user);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
            return userRes;
        }).filter(Objects::nonNull).collect(Collectors.toList());
        return userResList;
    }

    @PostMapping("/selectByPrimaryKey")
    @OperationAnnotation(content = "Feign暴露接口：根据userID查询")
    public com.bbzn.user.comment.User selectByPrimaryKey(@RequestBody Long id) throws Exception {
        User user = userService.selectByPrimaryKey(id);
        com.bbzn.user.comment.User userRes = new com.bbzn.user.comment.User();
        BeanUtils.copyProperties(userRes,user);
        return userRes;
    }

    @PostMapping("/updateByPrimaryKeySelective")
    @OperationAnnotation(content = "Feign暴露接口：根据userID修改数据")
    public int updateByPrimaryKeySelective(@RequestBody User record) throws Exception {
        return userService.updateByPrimaryKeySelective(record);
    }

    @PostMapping("/selectSubIdByPid")
    @OperationAnnotation(content = "Feign暴露接口：根据父id查询子id列表")
    public List<Long> selectSubIdByPid(@RequestBody Long pid) throws Exception{
        return userService.selectSubIdByPid(pid);
    }

    @PostMapping("/selectPidById")
    @OperationAnnotation(content = "Feign暴露接口：根据子id查询所有的父id")
    public List<Long> selectPidById(@RequestBody Long id) {
        return userService.selectPidById(id);
    }


    @PostMapping("/getUser")
    @OperationAnnotation(content = "查询用户")
    public BaseResponse getUser(HttpServletRequest request) throws Exception {
        String secretKey = commonService.getWebSalt(request);
        Long id = commonService.getUserId(request);
        String language = MayiktJwtUtils.getLanguage(request, secretKey);
        List<UserInfoDTO> userList = userService.selectByPid(id);
        SystemParam systemParam = systemParamByCacheService.getValues(CrudConstant.CRUD_ENUM, CrudConstant.SELECT_SUCCESS_PREFIX + language);
        return setResultSuccess(systemParam.getMassage(), userList);
    }

    @PostMapping("/addUser")
    @OperationAnnotation(content = "添加用户")
    public BaseResponse addUser(HttpServletRequest request, @RequestBody UserRoleVO user) throws Exception {
        String secretKey = commonService.getWebSalt(request);
        Long id = commonService.getUserId(request);
        String language = MayiktJwtUtils.getLanguage(request, secretKey);
        user.setPid(id);
        if (!OptionalBean.ofNullable(user.getUsername()).isPresent()) {
            SystemParam systemParam = systemParamByCacheService.getValues(UserConstant.USER_ENUM, UserConstant.USER_UN_NAME_PREFIX + language);
            throw new DefinitException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, systemParam.getMassage());
        }
        String password = user.getPassword();
        if (!OptionalBean.ofNullable(password).isPresent()) {
            SystemParam systemParam = systemParamByCacheService.getValues(UserConstant.USER_ENUM, UserConstant.USER_UN_PWD_PREFIX + language);
            throw new DefinitException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, systemParam.getMassage());
        }
        if (!OptionalBean.ofNullable(password).isPresent()) {
            SystemParam systemParam = systemParamByCacheService.getValues(UserConstant.USER_ENUM, UserConstant.USER_UN_PWD_PREFIX + language);
            throw new DefinitException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, systemParam.getMassage());
        }
        if (!OptionalBean.ofNullable(user.getPhone()).isPresent()) {
            SystemParam systemParam = systemParamByCacheService.getValues(UserConstant.USER_ENUM, UserConstant.PHO_UN_PHONE_PREFIX + language);
            throw new DefinitException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, systemParam.getMassage());
        }
        if (!OptionalBean.ofNullable(user.getEmail()).isPresent()) {
            SystemParam systemParam = systemParamByCacheService.getValues(UserConstant.USER_ENUM, UserConstant.PHO_UN_EMAIL_PREFIX + language);
            return setResultError(systemParam.getCode(), systemParam.getMassage());
        }
        if (!EmailUtil.checkEmail(user.getEmail())) {
            SystemParam systemParam = systemParamByCacheService.getValues(UserConstant.USER_ENUM, UserConstant.USER_EMAIL_ERROR_PREFIX + language);
            return setResultError(systemParam.getCode(), systemParam.getMassage());
        }
        if (!OptionalBean.ofNullable(user.getRoleId()).isPresent()) {
            SystemParam systemParam = systemParamByCacheService.getValues(RoleConstant.ROLE_ENUM, RoleConstant.ROLE_NO_ID_PREFIX + language);
            throw new DefinitException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, systemParam.getMassage());
        }
        if (!PhoneFormatCheckUtils.isPhoneLegal(user.getPhone())) {
            SystemParam systemParam = systemParamByCacheService.getValues(UserConstant.USER_ENUM, UserConstant.PHO_NUM_PREFIX + language);
            return setResultError(systemParam.getCode(), systemParam.getMassage());
        }
        // 验证角色id
        Role role = roleService.selectByPrimaryKey(user.getRoleId());
        if (null == role) {
            SystemParam systemParam = systemParamByCacheService.getValues(RoleConstant.ROLE_ENUM, RoleConstant.ROLE_NO_ID_PREFIX + language);
            throw new DefinitException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, systemParam.getMassage());
        }

        if (null != user.getTenantId() && !"".equals(user.getTenantId())) {
            // 验证公司id
            Tenant tenant = tenantService.selectByPrimaryKey(user.getTenantId());
            if (null == tenant) {
                SystemParam systemParam = systemParamByCacheService.getValues(TenantConstant.TENANT_ENUM, TenantConstant.TENANT_ID_INPUT_PREFIX + language);
                throw new DefinitException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, systemParam.getMassage());
            }
        }

        // 手机号 不得重复
        User query = new User();
        query.setPhone(user.getPhone());
        int result = userService.selectCountBySelective(query);
        if (result > 0) {
            SystemParam systemParam = systemParamByCacheService.getValues(UserConstant.USER_ENUM, UserConstant.PHO_PWD_NOT_NATCH_PREFIX + language);
            return setResultError(systemParam.getCode(), systemParam.getMassage());
        }

        // 密码校验
        if (password.matches("^.*[\\s]+.*$") || password.matches(".*\\s+$")) {
            SystemParam systemParam = systemParamByCacheService.getValues(UserConstant.USER_ENUM, UserConstant.PWD_SPACES_PREFIX + language);
            throw new DefinitException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, systemParam.getMassage());

        }
        if (!password.matches("^[a-zA-Z0-9\\!\\@\\#\\,\\.\\;\\:\\+\\=\\-\\_]+$")) {
            SystemParam systemParam = systemParamByCacheService.getValues(UserConstant.USER_ENUM, UserConstant.PWD_COMBINATION_PREFIX + language);
            throw new DefinitException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, systemParam.getMassage());
        }
        if (password.length() < 8 || password.length() > 16) {
            SystemParam systemParam = systemParamByCacheService.getValues(UserConstant.USER_ENUM, UserConstant.PWD_LENGTH_PREFIX + language);
            throw new DefinitException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, systemParam.getMassage());
        }
        if (password.matches("^(?:\\d+|[a-zA-Z]+|[!@#$%^&]+)$")) {
            SystemParam systemParam = systemParamByCacheService.getValues(UserConstant.USER_ENUM, UserConstant.PWD_STRENGTH_PREFIX + language);
            throw new DefinitException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, systemParam.getMassage());
        }

        if (!OptionalBean.ofNullable(user.getState()).isPresent()) {
            user.setState(1);
        }
        User record = BabaBeanUtils.voToDto(user, User.class);
        record.setPassword(MD5Util.encode(record.getPassword()));
        record.setCreateTime(new Date());
        record.setCreateBy(MayiktJwtUtils.getUsername(request, secretKey));
        userService.insert(record);
        //获取主键id
        Long userId = record.getId();
        UserRole param = new UserRole();
        param.setUserId(userId);
        param.setRoleId(user.getRoleId());
        userRoleService.insert(param);
        SystemParam systemParam = systemParamByCacheService.getValues(CrudConstant.CRUD_ENUM, CrudConstant.ADD_SUCCESS_PREFIX + language);
        return setResultSuccess(systemParam.getMassage());
    }


    @PostMapping("/updateUser")
    @OperationAnnotation(content = "修改用户")
    public BaseResponse updateUser(HttpServletRequest request, @RequestBody UserRoleVO user) throws Exception {
        String secretKey = commonService.getWebSalt(request);
        String language = MayiktJwtUtils.getLanguage(request, secretKey);
        if (!OptionalBean.ofNullable(user.getId()).isPresent()) {
            SystemParam systemParam = systemParamByCacheService.getValues(UserConstant.USER_ENUM, UserConstant.USER_UN_ID_PREFIX + language);
            throw new DefinitException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, systemParam.getMassage());
        }
        if (OptionalBean.ofNullable(user.getPhone()).isPresent()) {

            if (!PhoneFormatCheckUtils.isPhoneLegal(user.getPhone())) {
                SystemParam systemParam = systemParamByCacheService.getValues(UserConstant.USER_ENUM, UserConstant.PHO_NUM_PREFIX + language);
                return setResultError(systemParam.getCode(), systemParam.getMassage());
            }
            // 手机号 不得重复
            User query = new User();
            query.setPhone(user.getPhone());
            int result = userService.selectCountBySelective(query);
            if (result > 0) {
                SystemParam systemParam = systemParamByCacheService.getValues(UserConstant.USER_ENUM, UserConstant.PHO_PWD_NOT_NATCH_PREFIX + language);
                return setResultError(systemParam.getCode(), systemParam.getMassage());
            }
        }
        String password = user.getPassword();
        if (OptionalBean.ofNullable(password).isPresent()) {
            // 密码校验
            if (password.matches("^.*[\\s]+.*$") || password.matches(".*\\s+$")) {
                SystemParam systemParam = systemParamByCacheService.getValues(UserConstant.USER_ENUM, UserConstant.PWD_SPACES_PREFIX + language);
                throw new DefinitException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, systemParam.getMassage());
            }
            if (!password.matches("^[a-zA-Z0-9\\!\\@\\#\\,\\.\\;\\:\\+\\=\\-\\_]+$")) {
                SystemParam systemParam = systemParamByCacheService.getValues(UserConstant.USER_ENUM, UserConstant.PWD_COMBINATION_PREFIX + language);
                throw new DefinitException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, systemParam.getMassage());
            }
            if (password.length() < 8 || password.length() > 16) {
                SystemParam systemParam = systemParamByCacheService.getValues(UserConstant.USER_ENUM, UserConstant.PWD_LENGTH_PREFIX + language);
                throw new DefinitException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, systemParam.getMassage());
            }
            if (password.matches("^(?:\\d+|[a-zA-Z]+|[!@#$%^&]+)$")) {
                SystemParam systemParam = systemParamByCacheService.getValues(UserConstant.USER_ENUM, UserConstant.PWD_STRENGTH_PREFIX + language);
                throw new DefinitException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, systemParam.getMassage());
            }
            user.setPassword(MD5Util.encode(user.getPassword()));
        }
        if (null != user.getTenantId() && !"".equals(user.getTenantId())) {
            // 验证公司id
            Tenant tenant = tenantService.selectByPrimaryKey(user.getTenantId());
            if (null == tenant) {
                SystemParam systemParam = systemParamByCacheService.getValues(TenantConstant.TENANT_ENUM, TenantConstant.TENANT_ID_INPUT_PREFIX + language);
                throw new DefinitException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, systemParam.getMassage());
            }
        }
        user.setUpdateTime(new Date());
        user.setUpdateBy(MayiktJwtUtils.getUsername(request, secretKey));
        userService.updateByPrimaryKeySelective(user);
        SystemParam systemParam = systemParamByCacheService.getValues(CrudConstant.CRUD_ENUM, CrudConstant.MODIFY_SUCCESS_PREFIX + language);
        return setResultSuccess(systemParam.getMassage());
    }

    @PostMapping("/delUser")
    @OperationAnnotation(content = "删除用户")
    public BaseResponse delUser(HttpServletRequest request, @RequestBody User user) throws Exception {
        String secretKey = commonService.getWebSalt(request);
        String language = MayiktJwtUtils.getLanguage(request, secretKey);
        if (!OptionalBean.ofNullable(user.getId()).isPresent()) {
            SystemParam systemParam = systemParamByCacheService.getValues(UserConstant.USER_ENUM, UserConstant.USER_UN_ID_PREFIX + language);
            throw new DefinitException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, systemParam.getMassage());
        }
        // 查询是否存在子账号
        int count = userService.selectSubOneCount(user.getId());
        if (count > 0) {
            SystemParam systemParam = systemParamByCacheService.getValues(UserConstant.USER_ENUM, UserConstant.DEL_ERROR_EXIST_SUB_PREFIX + language);
            throw new DefinitException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, systemParam.getMassage());
        }
        boolean flag = deviceClient.isHasDeviceByUsers(user.getId());
        if (flag) {
            SystemParam systemParam = systemParamByCacheService.getValues(UserConstant.USER_ENUM, UserConstant.DEL_ERROR_EXIST_DEVICE_PREFIX + language);
            throw new DefinitException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, systemParam.getMassage());
        }
        flag = fenceClient.isHasFenceByUsers(user.getId());
        if (flag) {
            SystemParam systemParam = systemParamByCacheService.getValues(UserConstant.USER_ENUM, UserConstant.DEL_ERROR_EXIST_FENCE_PREFIX + language);
            throw new DefinitException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, systemParam.getMassage());
        }
        userRoleService.removeByUserId(user.getId());
        userService.deleteByPrimaryKey(user.getId());
        SystemParam systemParam = systemParamByCacheService.getValues(CrudConstant.CRUD_ENUM, CrudConstant.DELETE_SUCCESS_PREFIX + language);
        return setResultSuccess(systemParam.getMassage());
    }

    @OperationAnnotation(content = "退出登录")
    @PostMapping(value = "/loginOut")
    public BaseResponse loginOut(HttpServletRequest request) throws Exception {
        String secretKey = commonService.getWebSalt(request);
        String language = MayiktJwtUtils.getLanguage(request, secretKey);
        redisUtil.delete(RedisConstant.PREFIX_WEB);
        redisUtil.delete(request.getHeader(RedisConstant.HEADER));
        SystemParam systemParam = systemParamByCacheService.getValues(LoginConstant.LOGIN_ENUM, LoginConstant.EXIT_LOGIN_SUCCESS_PREFIX + language);
        return setResultSuccess(systemParam.getMassage());
    }

    /**
     * 修改密码
     *
     * @param changeVo
     * @return
     * @throws Exception
     */
    @OperationAnnotation(content = "修改密码")
    @PostMapping(value = "/changePassword")
    public BaseResponse changePassword(@RequestBody ChangeVO changeVo, HttpServletRequest request) throws Exception {
        String secretKey = commonService.getWebSalt(request);
        String language = MayiktJwtUtils.getLanguage(request, secretKey);
        SystemParam systemParam = null;
        if (!OptionalBean.ofNullable(changeVo.getPhone()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(UserConstant.USER_ENUM, UserConstant.PHO_UN_PHONE_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        if (!OptionalBean.ofNullable(changeVo.getOldPwd()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(ChangeConstant.CHANGE_ENUM, ChangeConstant.CHANGE_UN_OLD_PWD_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        if (!OptionalBean.ofNullable(changeVo.getNewPwd()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(ChangeConstant.CHANGE_ENUM, ChangeConstant.CHANGE_UN_NEW_PWD_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }

        // 校验旧密码
        User user = new User();
        user.setPhone(changeVo.getPhone());
        List<User> userList = userService.findByAll(user);
        if (CollectionUtils.isEmpty(userList)) {
            systemParam = systemParamByCacheService.getValues(UserConstant.USER_ENUM, UserConstant.PHO_USER_NOT_EXIST_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        //把用户输入的密码加密然后跟数据库的密码做校验
        String oldPwd = MD5Util.encode(changeVo.getOldPwd());
        if (!userList.get(0).getPassword().equals(oldPwd)) {
            systemParam = systemParamByCacheService.getValues(ChangeConstant.CHANGE_ENUM, ChangeConstant.CHANGE_OLD_PWD_ERROR_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }

        // 密码校验
        if (changeVo.getNewPwd().matches("^.*[\\s]+.*$") || changeVo.getNewPwd().matches(".*\\s+$")) {
            systemParam = systemParamByCacheService.getValues(UserConstant.USER_ENUM, UserConstant.PWD_SPACES_PREFIX + language);
            throw new DefinitException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, systemParam.getMassage());

        }
        if (!changeVo.getNewPwd().matches("^[a-zA-Z0-9\\!\\@\\#\\,\\.\\;\\:\\+\\=\\-\\_]+$")) {
            systemParam = systemParamByCacheService.getValues(UserConstant.USER_ENUM, UserConstant.PWD_COMBINATION_PREFIX + language);
            throw new DefinitException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, systemParam.getMassage());
        }
        if (changeVo.getNewPwd().length() < 8 || changeVo.getNewPwd().length() > 16) {
            systemParam = systemParamByCacheService.getValues(UserConstant.USER_ENUM, UserConstant.PWD_LENGTH_PREFIX + language);
            throw new DefinitException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, systemParam.getMassage());
        }
        if (changeVo.getNewPwd().matches("^(?:\\d+|[a-zA-Z]+|[!@#$%^&]+)$")) {
            systemParam = systemParamByCacheService.getValues(UserConstant.USER_ENUM, UserConstant.PWD_STRENGTH_PREFIX + language);
            throw new DefinitException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, systemParam.getMassage());
        }

        // 修改密码
        userList.stream().forEach(p -> {
            p.setPassword(MD5Util.encode(changeVo.getNewPwd()));
        });
        userService.updateBatchSelective(userList);
        systemParam = systemParamByCacheService.getValues(CrudConstant.CRUD_ENUM, CrudConstant.MODIFY_SUCCESS_PREFIX + language);
        return setResultSuccess(systemParam.getMassage());
    }

    /**
     * 公司账号操作-获取申请列表
     * 普通用户账号操作-获取邀请列表
     * tenant-phone 要和公司账号 user-phone一致 （user审批人）
     *
     * @return
     * @throws Exception
     */
    @OperationAnnotation(content = "获取申请和邀请列表")
    @PostMapping(value = "/getUserProcessListBy")
    public BaseResponse getUserProcessListByCompany(HttpServletRequest request) throws Exception {
        String secretKey = commonService.getWebSalt(request);
        String language = MayiktJwtUtils.getLanguage(request, secretKey);
        Long userId = commonService.getUserId(request);
        SystemParam systemParam = null;

        List<UserProcessDTO> userProcessDTOList = new ArrayList<>();
        User user = userService.selectByPrimaryKey(userId);
        UserProcess userProcess = new UserProcess();
        if (null == user.getTenantId() && "".equals(user.getTenantId())){   //租户id为空则是用户
            userProcess.setUserPhone(user.getPhone());
            userProcess.setType(1);
            userProcessDTOList = userProcessService.selUserProcessListByUser(userProcess);
            systemParam = systemParamByCacheService.getValues(CrudConstant.CRUD_ENUM, CrudConstant.SELECT_SUCCESS_PREFIX + language);
            return setResultSuccess(systemParam.getMassage(), userProcessDTOList);
        }

        userProcess.setTenantPhone(user.getPhone());
        userProcess.setType(2);
        userProcessDTOList = userProcessService.selUserProcessListByCompany(userProcess);

        systemParam = systemParamByCacheService.getValues(CrudConstant.CRUD_ENUM, CrudConstant.SELECT_SUCCESS_PREFIX + language);
        return setResultSuccess(systemParam.getMassage(), userProcessDTOList);
    }

    /**
     * 公司邀请用户
     * tenant-phone 要和公司账号 user-phone一致 （user审批人）
     *
     * @param reqVO
     * @return
     * @throws Exception
     */
    @OperationAnnotation(content = "公司邀请用户")
    @PostMapping(value = "/companyJoinUser")
    public BaseResponse companyJoinUser(@RequestBody UserProcessVO reqVO, HttpServletRequest request) throws Exception {
        String secretKey = commonService.getWebSalt(request);
        String language = MayiktJwtUtils.getLanguage(request, secretKey);
        String userName = MayiktJwtUtils.getUsername(request, secretKey);
        Long userId = commonService.getUserId(request);
        SystemParam systemParam = null;
        //用户的手机号
        if (!OptionalBean.ofNullable(reqVO.getUserPhone()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(UserConstant.USER_ENUM, UserConstant.PHO_UN_PHONE_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        //公司账号手机号
        if (!OptionalBean.ofNullable(reqVO.getTenantPhone()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(UserConstant.USER_ENUM, UserConstant.PHO_UN_PHONE_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        User us = userService.selectByPrimaryKey(userId);
        //先验证当前用户是否是公司账号
        if (null == us.getTenantId() || "".equals(us.getTenantId())){
            systemParam = systemParamByCacheService.getValues(UserConstant.USER_ENUM, UserConstant.USER_NO_TENANT_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }

        User user = userService.selectByPhone(reqVO.getUserPhone());
        if (null == user){
            systemParam = systemParamByCacheService.getValues(UserConstant.USER_ENUM, UserConstant.USER_PHONE_NO_DATA_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        UserProcess userProcess = new UserProcess();
        userProcess.setTenantPhone(reqVO.getTenantPhone());
        userProcess.setUserPhone(reqVO.getUserPhone());
        userProcess.setType(1);
        userProcess.setState(0);
        userProcess.setCreateTime(new Date());
        userProcess.setCreatedBy(userName);
        userProcessService.insert(userProcess);
        systemParam = systemParamByCacheService.getValues(CrudConstant.CRUD_ENUM, CrudConstant.ADD_SUCCESS_PREFIX + language);
        return setResultSuccess(systemParam.getMassage());
    }

    /**
     * 用户申请加入公司
     * tenant-phone 要和公司账号 user-phone一致 （user审批人）
     *
     * @param reqVO
     * @return
     * @throws Exception
     */
    @OperationAnnotation(content = "用户申请加入公司")
    @PostMapping(value = "/userJoinCompany")
    public BaseResponse userJoinCompany(@RequestBody UserProcessVO reqVO, HttpServletRequest request) throws Exception {
        String secretKey = commonService.getWebSalt(request);
        String language = MayiktJwtUtils.getLanguage(request, secretKey);
        String userName = MayiktJwtUtils.getUsername(request, secretKey);
        SystemParam systemParam = null;
        //当前用户的手机号
        if (!OptionalBean.ofNullable(reqVO.getUserPhone()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(UserConstant.USER_ENUM, UserConstant.PHO_UN_PHONE_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        //公司账号手机号
        if (!OptionalBean.ofNullable(reqVO.getTenantPhone()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(UserConstant.USER_ENUM, UserConstant.PHO_UN_PHONE_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        Tenant tenant = tenantService.selectByPhone(reqVO.getTenantPhone());
        User user = userService.selectByPhone(reqVO.getTenantPhone());
        if (null == tenant || null == user){
            //改手机号可能不是公司账号御用的手机号。
            systemParam = systemParamByCacheService.getValues(UserConstant.USER_ENUM, UserConstant.USER_PHONE_NO_DATA_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        UserProcess userProcess = new UserProcess();
        userProcess.setTenantPhone(reqVO.getTenantPhone());
        userProcess.setUserPhone(reqVO.getUserPhone());
        userProcess.setType(2);
        userProcess.setState(0);
        userProcess.setCreateTime(new Date());
        userProcess.setCreatedBy(userName);
        userProcessService.insert(userProcess);
        systemParam = systemParamByCacheService.getValues(CrudConstant.CRUD_ENUM, CrudConstant.ADD_SUCCESS_PREFIX + language);
        return setResultSuccess(systemParam.getMassage());
    }

    /**
     * 公司账号操作-获取申请列表
     * tenant-phone 要和公司账号 user-phone一致 （user审批人）
     *
     * @param reqVO
     * @return
     * @throws Exception
     */
    @OperationAnnotation(content = "修改UserProcess状态")
    @PostMapping(value = "/updateUserProcessState")
    public BaseResponse updateUserProcessState(@RequestBody UserProcessVO reqVO, HttpServletRequest request) throws Exception {
        String secretKey = commonService.getWebSalt(request);
        String language = MayiktJwtUtils.getLanguage(request, secretKey);
        String userName = MayiktJwtUtils.getUsername(request, secretKey);
        Long userId = commonService.getUserId(request);
        SystemParam systemParam = null;
        //UserProcess-ID
        if (!OptionalBean.ofNullable(reqVO.getId()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(UserConstant.USER_ENUM, UserConstant.PHO_UN_PHONE_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        if (!OptionalBean.ofNullable(reqVO.getState()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(UserConstant.USER_ENUM, UserConstant.PHO_UN_PHONE_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }

        UserProcess userProcess = new UserProcess();
        userProcess.setId(reqVO.getId());
        userProcess.setState(reqVO.getState());
        userProcessService.updateByPrimaryKeySelective(userProcess);

        //邀请：1、获取被邀请人(user_phone)的手机号，2、查到用户信息，修改该用户的pid
        //加入：1、获取申请人(user_phone)的手机号，2、查到用户信息，修改该用户的pid
        //同意时：修改用户pid
        UserProcess up = userProcessService.selectByPrimaryKey(reqVO.getId());
        if (reqVO.getState() == 1){
            User user = userService.selectByPhone(up.getUserPhone());
            user.setPid(userId);
            user.setUpdateTime(new Date());
            user.setUpdateBy(userName);
            userService.updateByPrimaryKeySelective(user);
        }
        systemParam = systemParamByCacheService.getValues(CrudConstant.CRUD_ENUM, CrudConstant.MODIFY_SUCCESS_PREFIX + language);
        return setResultSuccess(systemParam.getMassage());
    }

}
